﻿using UnityEngine;
using System.Collections;
using System.IO;
using System.Collections.Generic;
using System;
using UnityEditor;
using System.Xml;



namespace UnityEditor.EclipseEditor {
		
	public class ELProject {

		private string eclipseProjectPath;
		private XmlDocument xml;


		public ELProject(string eclipseProjectPath)
		{
			xml = new XmlDocument ();
			this.eclipseProjectPath = eclipseProjectPath;
			xml.Load (eclipseProjectPath + "/XUPE/AndroidManifest.xml");
		}

		public void Apply(Mod mod)
		{
			/*
			 * step 1: modify androidManifest.xml
			 * step 2: replace java file
			 * step 3: quote lib
			 */
			ApplyXml (mod);	
		}

		/// Manage the AndroidManifest.xml.
		public void ApplyXml(Mod mod)
		{

			//XmlNamespaceManager xnm = new XmlNamespaceManager (mod.Xml.NameTable);
			//xnm.AddNamespace ("a", "http://schemas.android.com/apk/res/android");
	
			XmlNodeList rootChildNodesList = mod.Xml.DocumentElement.ChildNodes;
			foreach (XmlNode rootChildNode in rootChildNodesList) {
				if (rootChildNode.Name == "add-element") {
					string targetNodeName = rootChildNode.Attributes ["target"].Value;
					XmlNode targetNode = xml.SelectSingleNode (@"//" + targetNodeName);
					XmlNodeList nodeList = mod.Xml.SelectSingleNode ("/root/add-element/element").ChildNodes;
					foreach (XmlNode node in nodeList) {
						targetNode.AppendChild (xml.ImportNode (node, true));
					}
				}
				if (rootChildNode.Name == "modify-element") {
					string targetNodeName = rootChildNode.Attributes ["target"].Value;
					XmlElement targetNode = (XmlElement)xml.SelectSingleNode (@"//" + targetNodeName);
					XmlNodeList propertyList = rootChildNode.ChildNodes;
					foreach (XmlNode propertyNode in propertyList)
					{
						string attributeName = propertyNode.Attributes ["name"].Value;
						string attributeValue = propertyNode.Attributes ["value"].Value;
						targetNode.SetAttribute (attributeName, attributeValue);
					}
				}

			}

			xml.Save (eclipseProjectPath + "/XUPE/AndroidManifest.xml");


		}

	}
	
}





